from tinystack.models import session
import uuid

class BaseComponent(object):
    model = None

    def _query(self, _session, field, value):
        return _session.query(self.model).filter(field==value).first()

    def search(self, uuid):
        instance = None
        with session() as _session:
            instance = self._query(_session, self.model.uuid, uuid)
            if not instance:
                instance = self._query(_session, self.model.id, uuid)
                if not instance:
                    instance = self._query(_session, self.model.name, uuid)
            return instance.uuid

    def add(self, *args, **kwargs):
        kwargs["uuid"] = str(uuid.uuid4())
        kwargs["status"] = "activate"
        with session() as _session:
            instance = self.model(**kwargs)
            _session.add(instance)

    def list(self):
        instances = []
        with session() as _session:
            instances = map(lambda x: x.todict(), _session.query(self.model).\
                filter(self.model.status == "activate").all())
        return instances

    def delete(self, uuid):
        with session() as _session:
            instance = self._query(_session, self.model.uuid, uuid)
            instance.status = "deleted"